
/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.oms.cart.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxk.oms.cart.domain.OmsCart;
import com.lxk.oms.cart.domain.bo.OmsCartBo;
import com.lxk.oms.cart.domain.vo.OmsCartVo;
import com.lxk.oms.cart.mapper.OmsCartMapper;
import com.lxk.oms.cart.service.IOmsCartService;
import com.lxk.service.pms.api.PmsServiceApi;
import com.lxk.service.pms.response.PmsProductSkuDto;
import com.lxk.service.pms.response.PmsProductSpuDto;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 用户购物车Service业务层处理
 *
 * @author LXK-RY5
 * @date 2024-08-22
 */
@RequiredArgsConstructor
@Service
public class OmsCartServiceImpl implements IOmsCartService {

    private final OmsCartMapper baseMapper;
    private final PmsServiceApi pmsServiceApi;

    /**
     * 查询IdList用户购物车Map
     */
    @Override
    public Map<Long, OmsCartVo> queryMapByIdList(List<Long> idList) {
        return this.queryByIdList(idList).stream().collect(Collectors.toMap(OmsCartVo::getId, v -> v));
    }

    /**
     * 查询用户购物车Map
     */
    @Override
    public Map<Long, OmsCartVo> queryMap(OmsCartBo bo) {
        return this.queryList(bo).stream().collect(Collectors.toMap(OmsCartVo::getId, v -> v));
    }

    /**
     * 查询用户购物车IdList
     */
    @Override
    public List<OmsCartVo> queryByIdList(List<Long> idList) {
        if (CollUtil.isEmpty(idList)) {
            return CollUtil.newArrayList();
        }
        LambdaQueryWrapper<OmsCart> lqw = Wrappers.lambdaQuery();
        lqw.in(OmsCart::getId, idList);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询用户购物车IdList
     */
    @Override
    public List<OmsCartVo> queryByIdList(List<Long> idList, Long userId) {
        if (CollUtil.isEmpty(idList)) {
            return CollUtil.newArrayList();
        }
        LambdaQueryWrapper<OmsCart> lqw = Wrappers.lambdaQuery();
        lqw.eq(OmsCart::getUserId, userId);
        lqw.in(OmsCart::getId, idList);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询用户购物车
     *
     * @param id 主键
     * @return 用户购物车
     */
    @Override
    public OmsCartVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询用户购物车列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户购物车分页列表
     */
    @Override
    public TableDataInfo<OmsCartVo> queryPageList(OmsCartBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OmsCart> lqw = buildQueryWrapper(bo);
        Page<OmsCartVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollUtil.isEmpty(result.getRecords())) {
            return TableDataInfo.build(result);
        }
        List<Long> spuIdList = result.getRecords().stream().map(OmsCartVo::getSpuId).distinct().collect(Collectors.toList());
        List<Long> skuIdList = result.getRecords().stream().map(OmsCartVo::getSkuId).distinct().collect(Collectors.toList());
        List<PmsProductSpuDto> spuList = pmsServiceApi.queryBySpuIdList(spuIdList, true).getData();
        List<PmsProductSkuDto> skuList = pmsServiceApi.queryBySkuIdList(skuIdList).getData();
        // 需要查询SKU
        Map<Long, PmsProductSpuDto> spuMap = spuList.stream().collect(Collectors.toMap(PmsProductSpuDto::getId, Function.identity()));
        Map<Long, PmsProductSkuDto> skuMap = skuList.stream().collect(Collectors.toMap(PmsProductSkuDto::getId, Function.identity()));
        result.getRecords().forEach(v -> {
            PmsProductSpuDto spu = spuMap.get(v.getSpuId());
            PmsProductSkuDto sku = skuMap.get(v.getSkuId());
            if (spu != null) {
                v.setDescription(spu.getDescription());
                v.setName(spu.getName());
            }
            if (sku != null) {
                v.setPrice(sku.getPrice());
                v.setImage(sku.getPicUrl());
            }
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的用户购物车列表
     *
     * @param bo 查询条件
     * @return 用户购物车列表
     */
    @Override
    public List<OmsCartVo> queryList(OmsCartBo bo) {
        LambdaQueryWrapper<OmsCart> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OmsCart> buildQueryWrapper(OmsCartBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OmsCart> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(OmsCart::getId);
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
            OmsCart::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.between(params.get("beginUpdateTime") != null && params.get("endUpdateTime") != null,
            OmsCart::getUpdateTime, params.get("beginUpdateTime"), params.get("endUpdateTime"));
        lqw.eq(bo.getMerId() != null, OmsCart::getMerId, bo.getMerId());
        lqw.eq(bo.getUserId() != null, OmsCart::getUserId, bo.getUserId());
        lqw.eq(bo.getSpuId() != null, OmsCart::getSpuId, bo.getSpuId());
        lqw.eq(bo.getSkuId() != null, OmsCart::getSkuId, bo.getSkuId());
        lqw.eq(bo.getCount() != null, OmsCart::getCount, bo.getCount());
        lqw.eq(bo.getSortStatus() != null, OmsCart::getSortStatus, bo.getSortStatus());
        return lqw;
    }

    /**
     * 新增用户购物车
     *
     * @param bo 用户购物车
     * @return 是否新增成功
     */
    @Lock4j
    @Override
    public Boolean insertByBo(OmsCartBo bo) {
        OmsCart add = MapstructUtils.convert(bo, OmsCart.class);
        validEntityBeforeSave(add);
        OmsCart omsCart = getCartItem(bo);
        boolean flag;
        if (ObjectUtil.isNull(omsCart)) {
            flag = baseMapper.insert(add) > 0;
            bo.setId(add.getId());
        } else {
            flag = this.addNumById(omsCart.getId(), bo.getUserId(), bo.getCount());
        }
        return flag;
    }

    private OmsCart getCartItem(OmsCartBo bo) {
        OmsCartBo cart = new OmsCartBo();
        cart.setUserId(bo.getUserId());
        cart.setSkuId(bo.getSkuId());
        cart.setSkuId(bo.getSkuId());
        cart.setMerId(bo.getMerId());
        LambdaQueryWrapper<OmsCart> lqw = buildQueryWrapper(cart);
        List<OmsCart> omsCarts = baseMapper.selectList(lqw);
        if (CollUtil.isNotEmpty(omsCarts)) {
            return omsCarts.get(BigDecimal.ZERO.intValue());
        }
        return null;
    }

    /**
     * 修改用户购物车
     *
     * @param bo 用户购物车
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(OmsCartBo bo) {
        OmsCart update = MapstructUtils.convert(bo, OmsCart.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OmsCart entity) {
        Assert.notNull(entity);
        if (entity.getMerId() == null) {
            throw new ServiceException("商家ID不能为空");
        }
        if (entity.getUserId() == null) {
            throw new ServiceException("用户ID不能为空");
        }
        if (entity.getSpuId() == null) {
            throw new ServiceException("商品ID不能为空");
        }
        if (entity.getSkuId() == null) {
            throw new ServiceException("商品规格ID不能为空");
        }
        if (entity.getCount() == null) {
            throw new ServiceException("商品数量不能为空");
        }
        PmsProductSpuDto spu = pmsServiceApi.queryBySpuId(entity.getSpuId()).getData();
        if (ObjectUtil.isNull(spu)) {
            throw new ServiceException("商品不存在");
        }
        PmsProductSkuDto sku = pmsServiceApi.queryBySkuId(entity.getSkuId()).getData();
        if (ObjectUtil.isNull(sku)) {
            throw new ServiceException("商品规格不存在");
        }
    }

    /**
     * 校验并批量删除用户购物车信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            if (CollUtil.isEmpty(ids)) {
                throw new ServiceException("请选择要删除的数据");
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Lock4j
    @Override
    public Boolean subNumById(Long id, Long userId, Integer num) {
        this.checkExist(id, userId);
        UpdateWrapper<OmsCart> updateWrapper = new UpdateWrapper<>();
        updateWrapper.setSql(StrUtil.format("count = count - {}", num));
        updateWrapper.last(StrUtil.format(" and (count - {} >= 1)", num));
        updateWrapper.eq("id", id).eq("user_id", userId);
        boolean update = baseMapper.update(updateWrapper) > 0;
        if (!update) {
            throw new ServiceException("减少购物车数量失败");
        }
        return update;
    }

    @Lock4j
    @Override
    public Boolean addNumById(Long id, Long userId, Integer num) {
        this.checkExist(id, userId);
        UpdateWrapper<OmsCart> updateWrapper = new UpdateWrapper<>();
        updateWrapper.setSql(StrUtil.format("count = count + {}", num));
        updateWrapper.eq("id", id).eq("user_id", userId);
        boolean update = baseMapper.update(updateWrapper) > 0;
        if (!update) {
            throw new ServiceException("更新购物车数量失败");
        }
        return update;
    }

    public void checkExist(Long id, Long userId) {
        Assert.notNull(id);
        Assert.notNull(userId);
        boolean exists = baseMapper.exists(Wrappers.<OmsCart>lambdaQuery().eq(OmsCart::getId, id).eq(OmsCart::getUserId, userId));
        if (!exists) {
            throw new ServiceException("购物车商品不存在");
        }
    }
}
